using System.Collections.Generic;
using Agatha.Common;
using Agatha.Common.Caching;
using Source.Common;

namespace  Source.Web.FrameWork
{

    public class Dispatcher : RequestDispatcher
    {
        private readonly IClientSideUserManager userManager;
        private readonly IFormsAuthentication formsAuthentication;

        public Dispatcher(IRequestProcessor requestProcessor, IClientSideUserManager userManager, IFormsAuthentication formsAuthentication ,
            ICacheManager cacheManager) : base(requestProcessor,cacheManager)
        {
            this.userManager = userManager;
            this.formsAuthentication = formsAuthentication;
        }

        protected override void BeforeSendingRequests(IEnumerable<Request> requestsToProcess)
        {
            foreach (var request in requestsToProcess)
            {
                AddVisitInformationIfAppropriate(request);
            }
        }

        protected override void DealWithSecurityException(ExceptionInfo exceptionDetail)
        {
            formsAuthentication.SignOut();
        }

        private void AddVisitInformationIfAppropriate(Request request)
        {
            var authenticatedRequest = request as AuthenticatedRequest;

            if (authenticatedRequest != null)
            {
                authenticatedRequest.Visit = userManager.GetVisit();
            }
        }

    }
    

}